package service.impl;

import Dao.BuyTicketsDao;
import Dao.impl.BuyTicketsDaoImpl;
import entity.Orders;
import entity.Ticket;
import entity.Train;
import service.BuyTicketsService;
import untils.Msg;
import untils.SqlCollection;

import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

public class BuyTicketsServiceImpl implements BuyTicketsService {
    private BuyTicketsDao buyTicketsDao = new BuyTicketsDaoImpl();

    private SqlCollection sqlCollection = new SqlCollection();
    static Scanner sc = new Scanner(System.in);

    @Override
    public ArrayList<Train> findTickesData(String startStation, String endStation, String time,int carStation){
        return buyTicketsDao.findTickesData(startStation, endStation, time,carStation);
    }

    @Override
    public Msg<Orders> updateTicketsData(int userId,String idCard, Train train, String seatNumber) {
        Msg<Ticket> msg = new Msg<>();
        Msg<Orders> order = new Msg<>();
        int ticketId = 0;
        try {
            sqlCollection.beginTransaction();
            //判断是否有票//当票数售罄或停止售票时提醒用户已经停止售票或者票已经售罄
            //查看是否开始售票
            buyTicketsDao.findBuyState(train.getTrainId());
            if ("SUCCEED".equals(Msg.msg)) {
                //查询是否有票
                buyTicketsDao.findTicketStation(train.getSeat().getSeatId());
                if ("SUCCEED".equals(Msg.msg)) {
                    //根据电话号码判断是否已经购票//票表里面有没有改用户信息用来判断是否已有别人代购//并且返回ticketId
                    ticketId = buyTicketsDao.findBuyTickets(idCard, train.getTrainId());
                    //根据身份证号码查询票中该人这辆火车的信息 ticket_id 用于判断是否已经有该订单
                    //判断是否购已经有相关订单，如果有查看是否支付，如果支付则返回重复购票，如果未支付提醒客户支付或取消支付。
                    order = buyTicketsDao.findBuyRecord(userId,train.getTrainId(),ticketId);
                    if ("未购票".equals(Msg.msg)) {
                        //判断座位号是否可选择 是执行座位号分配，不是自动赋值座位号
                        int res = buyTicketsDao.findSeatNumberFromTickets(seatNumber, train.getTrainId());
                        if (res > 0) {
                            msg.setMsg("您的座位号被占用，请重新占座");
                        } else {
                            msg = buyTicketsDao.updateTicketsData(userId,idCard,train,seatNumber);
                            //车的票数减1
                            buyTicketsDao.updateTicketNumber(train.getSeat().getSeatId());
                            ticketId = buyTicketsDao.findTicketId(idCard,train.getTrainId());
                            buyTicketsDao.updateOrderData(userId,train,ticketId);
                        }
                    } else if ("SUCCEED".equals(Msg.msg)) {
                        //查看订单是否已经支付
                        order = buyTicketsDao.findBuyRecord(userId,train.getTrainId(),ticketId);
                        if ("未支付".equals(order.getData().getStatus())) {
                            Msg.msg = "您还有一个订单未支付，请你确认是否支付";
                        } else {
                            Msg.msg = "您已经购票请勿重复购买";
                        }
                    }
                } else {
                    Msg.msg = "购票失败，票已经售罄";
                }
            } else {
                Msg.msg = "火车未开始售票，或者该辆汽车已出发";
            }
            //如果取消支付则票数+1，如果支付则票数-1；
            sqlCollection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlCollection.rollback();
        } finally {
            sqlCollection.closeConnection();
        }
        try {
            order = buyTicketsDao.findBuyRecord(userId,train.getTrainId(),ticketId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return order;
    }

    @Override
    public void paymentOk(Orders order) {
        buyTicketsDao.paymentOk(order);
    }

    //退票
    @Override
    public void returnTickets(Ticket ticket) {
        sqlCollection.beginTransaction();
        Date now = new Date();
        try {
            //首先查看当前时间是否已经过退票时间 获取要退火车票的运行状态和时间
            Train train = buyTicketsDao.findTrainData(ticket.getTrainId());
            if(now.before(train.getDepartureTime())){
                //删除车票信息
                buyTicketsDao.deleteTickets(ticket.getTicketId());
                if("SUCCEED".equals(Msg.msg)){
                    //查看是否有相关订单如果有则删除，如果没有则修改车票信息
                    int ticketId = buyTicketsDao.findOrder(ticket.getTicketId());
                    if(ticketId>0){
                        //删除订单信息
                        buyTicketsDao.deleteOrder(ticket.getTicketId());
                    }else {
                        buyTicketsDao.addSeatTicket(ticket.getTrainId(),ticket.getSeatType());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void rebook(Ticket ticket ,String idCard) {

        try{
            //根据该票查询未发车的该区间的车辆车票信息//还有票的
            ArrayList<Train> trains = findTickesData(ticket.getTrain().getStartStation(),ticket.getTrain().getEndStation(),null,2);
            if (!trains.isEmpty()){
                System.out.println("ListId: ");
                for(int i = 0;i<trains.size();i++){
                    System.out.println(i+"\t"+trains.get(i).show());
                }
                //查询有的话可以改签
                System.out.println("请选择你要改签的车次ListId：");
                int listId = sc.nextInt();
                Train train = trains.get(listId);
                //删除数据库相关车票信息，删除订单信息
                returnTickets(ticket);
                updateTicketsData(ticket.getUserId(),idCard,train,null);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlCollection.closeConnection();
        }
        //相关车辆座位+1//重新使用购票操作
    }
}
